package com.qiyun.framework.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.qiyun.framework.R;
import com.qiyun.framework.entity.FragmentInfo;

import java.util.Map;


/**
 * 公共调用Activity
 */

public class CommonFragmentActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private BaseFragment fragment;
    private int mPageValue=-1;
    public final static String BUNDLE_KEY_PAGE = "BUNDLE_KEY_PAGE";
    public final static String BUNDLE_KEY_ARGS = "BUNDLE_KEY_ARGS";

    public final static String BUNDLE_KEY_USER = "BUNDLE_KEY_USER";
    public static Map<Integer,FragmentInfo> mFragmentInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (mPageValue == -1) {
            mPageValue = getIntent().getIntExtra(BUNDLE_KEY_PAGE, 0);
        }
        initFragment(mPageValue, getIntent());

    }

    /**
     * 设置数据源,设置一次即可,可在初始化时设置
     * @param fragmentInfos
     */
    public static void setData(Map<Integer,FragmentInfo> fragmentInfos){
        mFragmentInfos=fragmentInfos;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    //初始化fragment
    protected void initFragment(int mPageValue,Intent data){
        if(mFragmentInfos==null || mFragmentInfos.size()==0) throw new NullPointerException("数据源为空");
        try {
            this.fragment=(BaseFragment) mFragmentInfos.get(mPageValue).getmClz().newInstance();
            //装载fragment
            if(fragment==null) throw new NullPointerException();
            setTitle(mFragmentInfos.get(mPageValue).getmTitle());
            Bundle args = data.getBundleExtra(BUNDLE_KEY_ARGS);
            if (args != null) {
                fragment.setArguments(args);
            }
            fragmentManager  = getSupportFragmentManager();
            FragmentTransaction transaction=fragmentManager.beginTransaction();
            transaction.replace(R.id.CommonContent, fragment);
            transaction.commit();

        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("generate fragment error" );
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
